#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/mman.h>

int main(int argc, char** argv) {
	/* mov eax, 0
	 * ret
	 *
	 * */
	unsigned char code[] = {0xb8, 0x00, 0x00, 0x00, 0x00, 0xc3};
	if (argc < 2) {
		fprintf(stderr, "Usage: %s <integer>\n", argv[0]);
		return 1;
	}

	int num = atoi(argv[1]);
	/*
	 * mov eax, <user's value>
	 * ret
	 * */
	memcpy(&code[1], &num, 4);
	void* mem = mmap(NULL, sizeof(code), PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
			 -1, 0);

	memcpy(mem, code, sizeof(code));
	mprotect(mem, sizeof(code), PROT_READ | PROT_EXEC);

	int (*funcptr)() = reinterpret_cast<int(*)()>(mem);

	printf("Your number was: %d\n", funcptr());

	return 0;
}
